import React, { PureComponent } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {
   	Table,
   	Row,
   	Col,
   	Card,
   	Form,
   	Input,
	Icon,
	Button,
	message,
} from 'antd';

const FormItem = Form.Item;
import styles from './ProResAuthList.less';

import CreateForm from './ProResAuthCreateForm';//新增表单
import UpdateForm from './ProResAuthUpdateForm';//修改表单
import ViewForm from './ProResAuthViewForm';//查看表单
import ResAuthTree from './ProResAuthTree';//资源树



//角色列表
function initTotalList(columns) {
  const totalList = [];
  columns.forEach(column => {
    if (column.needTotal) {
      totalList.push({ ...column, total: 0 });
    }
  });
   return totalList;
}

class StandardTable extends PureComponent {
  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  static getDerivedStateFromProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };
  
  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data = {}, rowKey, ...rest } = this.props;
    const { list = [], pagination } = data;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
    };

    const rowSelection = {
    	type: "radio",
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable} style={{float: 'left',width:'70%'}}>
        <Table
          rowKey={rowKey || 'id' || 'key'}
          rowSelection={rowSelection}
          dataSource={list}
          pagination={paginationProps}
          onChange={this.handleTableChange}
          {...rest}
        />
      </div>
    );
  }
}

const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['关闭', '运行中', '已上线', '异常'];
@connect(({ proresauth, loading }) => ({
    proresauth,
    loading: loading.models.proresauth,
}))
@Form.create()
class ProResAuthList extends PureComponent {
	state = {
        modalVisible: false,
        updateModalVisible: false,
        viewModalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        updateFormValues: {},
        viewFormValues: {},
        authId:[],
        resTree: [],
        addResTreeInfo:[],
        root_parentid:'000000000000'
    };

	columns = [
			 {
        title: '角色名称',
        dataIndex: 'auth_name',
        },        {
        title: '角色类型',
        dataIndex: 'auth_type',
        }, 
	];

  constructor(props) {
    super(props);
  }

  componentDidMount() {
	const { dispatch } = this.props;
    dispatch({
        type: 'proresauth/query_page_for_proauthority',
    });
    dispatch({
        type: 'proresauth/get_proresourcetree_by_levelcode',
        payload:{
        	parentid:this.state.root_parentid
        }
    });
  }

  componentWillUnmount() {

  }
  
handleModalVisible = (flag,record) => {
    this.setState({
        modalVisible: !!flag,
        addResTreeInfo: record || {},
    });
};

handleAdd = fields => {
    const { dispatch } = this.props;
    const { key,levelcode } = this.state.addResTreeInfo;
    dispatch({
        type: 'proresauth/insert_for_prores',
        payload: {
        	root_parentid:this.state.root_parentid,
        	parentid: key,
            levelcode: levelcode,
            name: fields.name,
            enname: fields.enname,
            handler: fields.handler,
            icon: fields.icon,
        },
    });

    message.success('添加成功');
    this.handleModalVisible();
};

handleUpdateModalVisible = (flag, record) => {
    this.setState({
        updateModalVisible: !!flag,
        updateFormValues: record || {},
    });
};

handleUpdate = fields => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
        type: 'proresauth/update_for_prores',
        payload: {
        	root_parentid:this.state.root_parentid,
            id: fields.id,
            parentid: fields.parentid,
            name: fields.name,
            enname: fields.enname,
            handler: fields.handler,
            icon: fields.icon,
            levelcode: fields.levelcode,
        },
    });

    message.success('修改成功');
    this.handleUpdateModalVisible();

};

handleDeleteRecord = record => {
        const { dispatch } = this.props;
        dispatch({
	        type: 'proresauth/delete_by_primarykey_for_prores',
	        payload: {
	        	root_parentid:this.state.root_parentid,
	        	recordid: record.id,
	        },
	        callback: () => {
		        this.setState({
		        	selectedRows: [],
		        });
	        },
        });
        message.success('删除成功');
};

handleViewModalVisible = (flag, record) => {
    this.setState({
        viewModalVisible: !!flag,
        viewFormValues: record || {},
    });
};

toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
        expandForm: !expandForm,
    });
};

handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
        formValues: {},
    });
    dispatch({
        type: 'proresauth/query_page_for_proauthority',
        payload: {},
    });
};


handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
        if (err) return;

    const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
    };

    this.setState({
        formValues: values,
    });

    dispatch({
        type: 'proresauth/query_page_for_proauthority',
        payload: values,
    });
});
};

handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
	    const newObj = { ...obj };
	    newObj[key] = getValue(filtersArg[key]);
    	return newObj;
	}, {});
    const params = {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
        ...formValues,
        ...filters,
    };
    if (sorter.field) {
        params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
        type: 'proresauth/query_page_for_proauthority',
        payload: params,
    });
};

handleSelectRows = rows => {
	const { dispatch } = this.props;
   	const authIdArray = new Array(); 
  	rows.map(item => {
		authIdArray.push(item.auth_id);
		return authIdArray
	})
  	this.setState({
        selectedRows: rows,
        authId: authIdArray
   	});
	dispatch({
        type: 'proresauth/get_all_proresourcerree_by_authid', 
        payload: {
  			auth_id:authIdArray
        }, 
        callback:(response) => {
        	this.setState({
    			resTree: response.list
    		}) 
        }
 	});
};

checkedTreeChild = checkedInfo => {
	const checkedTree = checkedInfo.checkedNodes;
	const checkedKeyArray = new Array();
	checkedTree.map(item => {
		checkedKeyArray.push(item.props.dataRef.key)
		return checkedKeyArray;
	})
	this.setState({
		resTree:checkedKeyArray
	})
}

handleResAuthSave = () => {
	const { authId,resTree} = this.state;
	const { dispatch } = this.props;
	const resTreeAuth = new Array();
	if(!authId || authId.length == 0 ) {
		message.warning("请选择要授权的角色!!!");
		return false;
	}
	const authIds = new Array();
	for(let i = 0;i < authId.length;i++) {
			authIds.push({
				id: authId[i]
			})
		for(let j = 0;j < resTree.length;j++) {
			resTreeAuth.push({
				auth_id: authId[i],
				res_id: resTree[j],
			})
		}
	}
	dispatch({
        type: 'proresauth/insert_batch_for_proresauth',
        payload: {
        	authids: authIds,
        	authids_resids: resTreeAuth
        },
  });
  message.success('授权成功');
}

renderAdvancedForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
        	<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				<Col md={8} sm={24}>
			        <FormItem label="角色名称">
			        {getFieldDecorator('auth_name')(<Input placeholder="请输入" />)}
					</FormItem>
		    	</Col>
				<Col md={8} sm={24}>
			        <FormItem label="角色类型">
			        {getFieldDecorator('auth_type')(<Input placeholder="请输入" />)}
					</FormItem>
		    	</Col>
    		</Row>
		    <div style={{ overflow: 'hidden' }}>
				<div style={{ marginBottom: 24 }}>
					<Button type="primary" htmlType="submit">
			        查询
			        </Button>
			        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
			        重置
			        </Button>
		        	<a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
		        		收起 <Icon type="up" />
		        	</a>
		        </div>
		    </div>
        </Form>
	);
}
renderSimpleForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
        	<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				<Col md={8} sm={24}>
				    <FormItem label="角色名称">
				        {getFieldDecorator('auth_name')(<Input placeholder="请输入" />)}
					</FormItem>
				</Col>
    			<Col md={8} sm={24}>
			        <FormItem label="角色类型">
			        {getFieldDecorator('auth_type')(<Input placeholder="请输入" />)}
					</FormItem>
		    	</Col>
			    <Col md={8} sm={24}>
			        <span className={styles.submitButtons}>
				        <Button type="primary" htmlType="submit">
				        查询
				        </Button>
				        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
				        重置
				        </Button>
				        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
				        展开 <Icon type="down" />
				        </a>
			        </span>
			    </Col>
        </Row>
        </Form>
);
}

    renderForm() {
        const { expandForm } = this.state;
        return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }
  render() {
  	const {
        proresauth: { data,resTree,checkedKeys },
        loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, viewModalVisible,  updateFormValues,  viewFormValues, addResTreeInfo  } = this.state;
   	const parentMethods = {
           handleAdd: this.handleAdd,
           handleModalVisible: this.handleModalVisible,
           addResTreeInfo: addResTreeInfo
    };
   	const parentRole = {
       	selectedRows: selectedRows,
       	checkedKeys: checkedKeys,
       	checkedTreeChild: this.checkedTreeChild,
       	handleModalVisible: this.handleModalVisible,
       	handleUpdateModalVisible: this.handleUpdateModalVisible,
       	handleDeleteRecord: this.handleDeleteRecord,
       	handleViewModalVisible: this.handleViewModalVisible,
       	dispatch: this.props.dispatch,
    };
    const updateMethods = {
        handleUpdateModalVisible: this.handleUpdateModalVisible,
        handleUpdate: this.handleUpdate,
    };
    const viewMethods = {
        handleViewModalVisible: this.handleViewModalVisible
    };
    return (
            <PageHeaderWrapper title="角色资源信息列表">
            <Card bordered={false}>
            <div className={styles.proMenutableList} style={{position:'relative'}}>
            {/*<div className={styles.proMenutableListForm}>{this.renderForm()}</div>*/}
            <div className={styles.proMenutableListOperator}>
            <Button icon="plus" type="primary" onClick={ this.handleResAuthSave }>
        分配资源
        </Button>
    </div>
    	
        {resTree && Object.keys(resTree).length ? (
        	<ResAuthTree {...parentRole} resTree={resTree}/>
        ) : null}
        <StandardTable
        rowKey={"auth_id"}
        selectedRows={selectedRows}
        loading={loading}
        data={data}
        columns={this.columns}
        onSelectRow={this.handleSelectRows}
        onChange={this.handleStandardTableChange}/>
    </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
		{updateFormValues && Object.keys(updateFormValues).length ? (
            <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            />
        ) : null}
		{viewFormValues && Object.keys(viewFormValues).length ? (
            <ViewForm
            {...viewMethods}
            viewModalVisible={viewModalVisible}
            values={viewFormValues}
            />
        ) : null}
    </PageHeaderWrapper>
    );
  }
}

export default ProResAuthList;